package com.xy.config;

import com.baidu.aip.face.AipFace;
import com.xy.tx.TxCommon;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class AipFaceClient {

	private volatile static AipFace aipFace;
	public static final String APP_ID = "17001064";
	public static final String API_KEY = "GqoY3zACpeiMdZqcm5TbnGkU";
	public static final String SECRET_KEY = "41TdpiWn1nlSQLNoFvPXMvCSKmwBGB9R";
	/**
	 * 唯一公开获取实例的方法（静态工厂方法）
	 *
	 * @return
	 */
	public static AipFace getUniqueInstance() {
		//第一个 if 语句用来避免 uniqueInstance 已经被实例化之后的加锁操作
		if (aipFace == null) {
			System.out.println("创建");
			aipFace = new AipFace(APP_ID, API_KEY, SECRET_KEY);
		}
		System.out.println("未创建");
		return aipFace;
	}
	/**
	 * 人脸比对1:N
	 */
	public static Long  faceSearch(String faceThreshold,String url,List<String> groupIdList) throws Exception {
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("match_threshold", faceThreshold);
//		options.put("quality_control", "NORMAL");
//		options.put("liveness_control", "LOW");
		options.put("max_user_num", "1");
		String image =  TxCommon.getPictureBase(url);
		String imageType = "BASE64";
		String groupIdStr = groupIdList.stream().collect(Collectors.joining(","));
		AipFace client = getUniqueInstance();
		JSONObject jsonObject = client.search(image, imageType, groupIdStr, options);
		log.info("请求百度人脸识别1:N返回结果：{}",jsonObject);
		if("SUCCESS".equals(jsonObject.getString("error_msg"))){
			JSONObject result = jsonObject.getJSONObject("result");
			JSONArray userList = result.getJSONArray("user_list");
			if(!userList.isNull(0)){
				return userList.getJSONObject(0).getLong("user_id");
			}
		}

		return null;
	}
	/**
	 * 人脸注册
	 */
	public static boolean  addFace(String userId,String groupId,String url) throws Exception {
		// 传入可选参数调用接口
		HashMap<String, String> options = new HashMap<String, String>();
//		options.put("quality_control", "NORMAL");
//		options.put("liveness_control", "LOW");
		options.put("action_type", "REPLACE");
		String image =  TxCommon.getPictureBase(url);
		String imageType = "BASE64";
		AipFace client = getUniqueInstance();
		// 人脸注册
		JSONObject res = client.addUser(image, imageType, groupId, userId, options);
		log.info("请求百度人脸注册返回结果：{}",res);
		if("SUCCESS".equals(res.getString("error_msg"))){
			return  true;
		}
		return  false;
	}

	public static boolean  addFaceURL(String userId,String groupId,String url)  {
		// 传入可选参数调用接口
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("quality_control", "NORMAL");
		options.put("liveness_control", "LOW");
		options.put("action_type", "REPLACE");
		String imageType = "URL";
		AipFace client = getUniqueInstance();
		// 人脸注册
		try {
			JSONObject res = client.addUser(url, imageType, groupId, userId, options);
			log.info("请求百度人脸注册返回结果：{}",res);
		} catch (Exception e) {
			log.error("百度人脸注册异常", e);
		}
		return  true;
	}

	/**
	 * 人脸更新
	 */
	public static boolean  upateFace(String userId,String groupId,String url) throws Exception {
		// 传入可选参数调用接口
		HashMap<String, String> options = new HashMap<String, String>();
//		options.put("quality_control", "NORMAL");
//		options.put("liveness_control", "LOW");
		options.put("action_type", "UPDATE");
		String image = TxCommon.getPictureBase(url);
		String imageType = "BASE64";
		AipFace client = getUniqueInstance();
		// 人脸注册
		JSONObject res = client.updateUser(image, imageType, groupId, userId, options);
		log.info("请求百度人脸更新返回结果：{}",res);
		return  true;
	}
	/**
	 * 人脸删除
	 */
	public static boolean  deleteFace(String userId,String groupId) {
		AipFace client = getUniqueInstance();
		// 人脸注册
		try {
			JSONObject res = client.deleteUser( groupId, userId, null);
			log.info("请求百度人脸删除返回结果：{}",res);
		} catch (Exception e) {
			log.error("请求百度人脸删除异常",e);
		}
		return  true;
	}

//	public static String getImageBase(String src) throws Exception {
//		URL url = new URL(src);
//		InputStream in = null;
//		byte[] data = null;
//		try {
//			in = url.openStream();
//			data = new byte[in.available()];
//			in.read(data);
//			in.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return Base64Util.encodeToString(data);
//	}

	public static void main(String[] args) {
		try {
//			addFace("1645439687389650946","1640611560205410306","http://172.30.101.203:9000/face/upload/20230411/5bc0a2cd6662229e25513425a4866908.png");
			addFace("1645355906284650498","1640611560205410306","http://172.30.101.203:9000/face/upload/20230411/ecf00ec7dcd7cd46e694fd8f6cccf8ac.png");
		} catch (Exception e) {

			throw new RuntimeException(e);
		}
	}
}
